
import { join } from 'path'
import mongoose from 'mongoose'
import glob from 'glob'
import config from '../../config'

mongoose.Promise = global.Promise

glob.sync(join(__dirname, '../database/admin', '**/*.js')).forEach(require)

export const database = app => {
    const { db } = config

    if (config.env === 'development') {
        mongoose.set('debug', true)
    }

    mongoose.connect(db, {
        useNewUrlParser: true,
        useUnifiedTopology: true
    }, (err) => {
        if (!err) console.log('数据库连接成功')
    })

    mongoose.connection.on('disconnected', () => {
        mongoose.connect(db, {
            useNewUrlParser: true,
            useUnifiedTopology: true
        })
    })

    mongoose.connection.on('error', err => {
        console.log(err)
    })

    mongoose.connection.once('open', () => {
        console.log('Connected to MongoDB ->', db)
    })
}